<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="bootstrap.css"/>
    <link rel="stylesheet" href="bootstrap-theme.css"/>
    <script src="jquery-3.1.1.min.js"></script>
    <title>inputMax</title>
    <style type="text/css">
        body{font-size:13px;}
        .frame{width:260px;}
        .title{padding:5px 0;}
        .txt{height:108px;
            width: 252px;
            border:#666 1px solid;
            padding:3px;
        }
    </style>
    <script type="text/javascript">
        $(function(){
            $("#txtMessage").maxLength(140,"divMaxNum");
        });
        jQuery.fn.maxLength=function(max,ele){
            this.each(function(){
                var type=this.tageName.toLowerCase();
                var inputType=this.type?this.type.toLowerCase():null;
                if(type=="input"&&inputType=="text"||inputType=="password"){
                    this.maxLength=max;
                }
                else if(type=="textarea"){
                    this.onkeypress=function(e){
                        var ev=e||event;
                        var keyCode=ev.keyCode;
                        return !(this.value.length>=max&&(keyCode==32||keyCode==13)&&!ev.ctrlKey&&!ev.altKey);
                    };
                    this.onkeyup=function(){
                        if(this.value.length>max){
                            this.value=this.value.substring(0,max);
                        }
                        $("#"+ele).html(max-this.value.length);
                    };
                    this.onchange=this.onkeyup;
                };
            });
        };
    </script>
</head>
<body>
<div class="frame">
    <div class="title">我要留言</div>
    <textarea id="txtMessage" class="txt"></textarea>
    <div align="right" id="divMaxNum">140</div>
</div>
</body>
</html>